package com.wl.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.wl.enums.UserType;
import com.wl.exception.BusinessException;
import com.wl.model.User;
import com.wl.service.UserService;
import com.wl.utils.PageUtil;
import com.wl.vo.UserAccount;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RequestMapping("/user")
@Controller
public class UserController {

    private final static Logger LOG = Logger.getLogger(UserController.class);

    @Autowired
    UserService userService;

    private String imageDir = "D:/data/image/";

    @PostMapping("/register")
    public ModelAndView register(UserAccount userAccount, MultipartFile file) throws IOException {
        String headPhoto = saveImage(file);
        User user = userAccount.getUser();
        if(user != null){
            user.setHeadPhoto(headPhoto);
        }
        final User register = userService.register(userAccount);
        final ModelAndView login = new ModelAndView("login");
        login.getModelMap().put("info", true);
        login.getModelMap().put("desc", "注册成功, 请登录");
        return login;
    }

    @GetMapping("/image/{imageName}")
    public void image(@PathVariable String imageName, HttpServletResponse resp, HttpServletRequest req) throws IOException {
        String extension = FilenameUtils.getExtension(req.getRequestURL().toString());
        Path path = Paths.get(imageDir, imageName+"."+extension);
        if(!path.toFile().exists()){
            //如果找不到就给个默认图片
            path = Paths.get(imageDir, "default.jpg");
        }
        Files.copy(path,resp.getOutputStream());
    }

    @PostMapping("/login")
    public Object login(UserAccount userAccount, HttpServletRequest request) {
        final User us = userService.login(userAccount);

        final ModelAndView modelAndView = new ModelAndView();

        //如果是超管, 跳后台管理页
        if (UserType.admin.name().equals(us.getType())) {
            modelAndView.setViewName("main");
            request.getSession().setAttribute("user", us);
            return modelAndView;
        }
        request.getSession().setAttribute("user", us);
        //普通用户 跳新闻展示页
        return "redirect:/newsInfo/allNewsInfo";
    }


    /***
     * 获取用户信息
     * */
    @GetMapping("/getUser")
    public ModelAndView getUser(long userId, boolean update, HttpServletRequest request) {
        request.getSession().setAttribute("user", userService.getUser(userId));
        final ModelAndView modelAndView = new ModelAndView();
        if (update) {
            modelAndView.addObject("isUpdate","update");
            modelAndView.setViewName("addAndUpdateUser");
            return modelAndView;
        }
        return modelAndView;
    }


    /***
     * 获取所用普通用户信息
     * */
    @GetMapping("/getLimitUser")
    public ModelAndView getLimitUser(PageUtil pageUtil, HttpServletRequest request) {
        PageUtil newPageUtil = this.getPageUtil(pageUtil);
        request.getSession().setAttribute("pageUtil", newPageUtil);
        request.getSession().setAttribute("userList", userService.getLimitUser(pageUtil));
        final ModelAndView modelAndView = new ModelAndView("userManage");
        return modelAndView;
    }

    /***
     * 删除用户
     * */
    @GetMapping("/deleteUser")
    public ModelAndView deleteUser(long userId, PageUtil pageUtil, HttpServletRequest request) {
        userService.deleteUser(userId);
        ModelAndView limitUser = this.getLimitUser(pageUtil, request);
        return limitUser;
    }

    /***
     * 修改用户
     * */
    @PostMapping("/updateUser")
    public ModelAndView updateUser(User user, PageUtil pageUtil, HttpServletRequest request) {
        userService.updateUser(user);
        ModelAndView limitUser = this.getLimitUser(pageUtil, request);
        return limitUser;
    }

    /***
     * 添加用户
     * */
    @PostMapping("/addUser")
    public ModelAndView addUser(User user, PageUtil pageUtil, HttpServletRequest request) {
        userService.addUser(user);
        ModelAndView limitUser = this.getLimitUser(pageUtil, request);
        return limitUser;
    }

    /***
     * 索搜
     * */
    @PostMapping("/findByUser")
    public ModelAndView findByUser(User user, HttpServletRequest request) {
        request.getSession().setAttribute("userList", userService.findByUser(user));
        final ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("userManage");
        return modelAndView;
    }

    @GetMapping("/logout")
    public String loginOut(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return "login";
    }


    private PageUtil getPageUtil(PageUtil pageUtil) {
        pageUtil.getPageCount(userService.getCountUser());
        if (pageUtil.getCurrentPage() == 0) {
            pageUtil.setCurrentPage(1);
        } else if (pageUtil.getCurrentPage() > pageUtil.getTotalPage()) {
            pageUtil.setCurrentPage(pageUtil.getCurrentPage() - 1);
        }
        pageUtil.setIndexPage((pageUtil.getCurrentPage() - 1) * pageUtil.getPageSize());
        return pageUtil;
    }

    public String saveImage(MultipartFile file) throws IOException {
        String imageFileName = createImageFileName(file);
        Path path = Paths.get(imageDir, imageFileName);
        Files.copy(file.getInputStream(),path);
        return imageFileName;
    }

    /**
     * 重新生成一个随机文件名
     * @param file 文件
     * @return 文件名
     */
    private String createImageFileName(MultipartFile file){
        return System.currentTimeMillis() + "." + FilenameUtils.getExtension(file.getOriginalFilename());
    }




}
